package com.mumulx.check.web.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/*
 *  Created by IntelliJ IDEA.
 *  User: 木木
 *  Date: 2020/10/20
 *  Time: 21:08
 *  用于创建图片验证码，验证码格式为四位数数字即  1000-9999
 */
public class VerifyCode {

    /*
     * @author mumulx
     * @creed: mumulx编写
     * @email: 2606964863@qq.com
     * @date 2020/10/20 21:14
     * @param width
     * @param height
     * @param verifyImg
     * @return java.lang.String
     */
    public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();

        graphics.fillRect(0, 0, width, height);//填充背景
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 18));
        StringBuilder builder = new StringBuilder();
        String checkCode = getNum() ; //2 1 3 4
        //验证码的每一位数字
        for(int i=0;i<checkCode.length();i++){
            builder.append(checkCode.charAt(i)+" "  )  ;
        }
        //绘制验证码
        graphics.setColor(Color.BLACK);
        graphics.drawString( builder.toString(), 5,17 );//绘制验证码

        Random random = new Random() ;
        //画干扰线
        for (int i = 0; i < 10; i++) {
            // 设置随机颜色
            graphics.setColor(getRandomColor());
            // 随机画线
            graphics.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }
        //添加噪点
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2, 2);
        }
        return checkCode;
    }

    /**
     * 随机取色
     */
  private static Color getRandomColor() {
      Random ran = new Random() ;//Math.random()  0-1
      int r = ran.nextInt(256) ;
      int g = ran.nextInt(256) ;
      int b = ran.nextInt(256) ;
      return new Color(r,g,b) ;//red green blue  0-255
    }
    //产生验证码值
    public static String getNum()
    {
        //  0-8999   1000-9999
        int ran = (int)( Math.random()*9000) +1000 ;
        return String.valueOf(ran) ;
    }
}
